package com.binc.testspring.common.convert.easyExcel;

import com.alibaba.excel.converters.AutoConverter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import com.binc.testspring.common.excel.TimeFormatConfig;

import java.text.ParseException;
import java.util.Date;

/**
 * easyExcel导出时间格式化器 实现类
 *      继承 easyexcel的类，重写一些方法
 */
public class TimeMillisFormatConverter extends AutoConverter {


    private final static String FORMATTER = "yyyy-MM-dd HH:mm:ss";

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Class supportJavaTypeKey() {
        return Long.class;
    }

    @Override
    public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        try {
            if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
                return DateUtils.parseDate(cellData.getStringValue(), null).getTime();
            } else {
                return DateUtils.parseDate(cellData.getStringValue(),
                        contentProperty.getDateTimeFormatProperty().getFormat()).getTime();
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {

        if (value != null) {
            if (value instanceof Long) {
                TimeFormatConfig annotation = contentProperty.getField().getAnnotation(TimeFormatConfig.class);
                return new CellData(DateUtils.format(new Date((Long) value), annotation != null ? annotation.format() : FORMATTER));
            }
        }
        return new CellData(CellDataTypeEnum.EMPTY);
    }
}